<template>
  <div class="taskplan">
    <el-card class="hover">
      <!-- 任务列表 -->
      <div class="show-plan">
        <div class="add-plan"><el-button type="primary" size="mini" @click="addTaskPlan">添加</el-button></div>
        <div class="form">
          <el-table :data="tableData" border stripe style="width: 100%">
            <el-table-column prop="count" width="120" label="序号" align="center"> </el-table-column>
            <el-table-column prop="planNumber" width="120" label="计划编号" align="center"> </el-table-column>
            <el-table-column prop="planName" width="120" label="计划名称" align="center"> </el-table-column>
            <el-table-column prop="startTime" width="120" label="开始时间" align="center"> </el-table-column>
            <el-table-column prop="endTime" width="120" label="结束时间" align="center"> </el-table-column>
            <el-table-column prop="typeName" width="120" label="任务类型" align="center"> </el-table-column>
            <el-table-column prop="patrolGrid" width="120" label="巡查范围" align="center"> </el-table-column>
            <el-table-column prop="patrolSubject" width="120" label="巡查主体" align="center"> </el-table-column>
            <el-table-column prop="subjectType" width="120" label="主体类型" align="center"> </el-table-column>
            <el-table-column prop="frequencyCount" width="120" label="实施周期" align="center"> </el-table-column>
            <el-table-column width="120" label="状态" align="center">
              <template slot-scope="scope">
                <span class="finishactive active" v-if="scope.row.status == 1"></span>
                <span class="noactive active" v-else></span>
                <span style="margin-left: 10px">{{ taskPlanStatus[scope.row.status] }}</span>
              </template>
            </el-table-column>
            <el-table-column width="120" label="任务进度" align="center">
              <template slot-scope="scope">
                <span class="noactive active" v-if="scope.row.plannedProgress == 1"></span>
                <span class="onactive active" v-else-if="scope.row.plannedProgress == 2"></span>
                <span class="finishactive active" v-else-if="scope.row.plannedProgress == 3"></span>
                <span class="outactive active" v-else></span>
                <span style="margin-left: 10px">{{ plannedProgressOption[scope.row.plannedProgress] }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="lastTime" width="120" label="创建时间" align="center"> </el-table-column>
            <el-table-column fixed="right" width="300" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="info" @click="openDetailWin(scope.row)" size="mini">详情</el-button>
                <el-button type="warning" @click="openEditWin(scope.row)" size="mini">编辑</el-button>
                <el-button type="danger" @click="openDeleteWin(scope.row)" size="mini">删除</el-button>
                <el-button type="success" @click="openDistributionWin(scope.row)" size="mini">处置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 页码 -->
      <el-pagination
        class="pageBox"
        background
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        layout="sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </el-card>
    <!-- 新增任务 -->
    <el-dialog :title="changeStatus ? '新增计划' : '修改计划'" :visible.sync="createTaskWin" width="40%">
      <el-row>
        <el-col :span="18">
          <div class="grid-content bg-purple">
            <el-form label-position="right" label-width="120px" :model="taskFormData">
              <el-form-item label="计划名称：">
                <el-input v-model="taskFormData.planName"></el-input>
              </el-form-item>
              <el-form-item label="开始时间：">
                <div class="block">
                  <el-date-picker
                    v-model="taskFormData.startTime"
                    type="date"
                    placeholder="选择日期："
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="结束时间：">
                <div class="block">
                  <el-date-picker
                    v-model="taskFormData.endTime"
                    type="date"
                    placeholder="选择日期："
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="任务类型：">
                <el-select v-model="taskFormData.taskTypeId" clearable placeholder="请选择任务类型" style="width: 100%">
                  <el-option v-for="item in typeOption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- 联级选择器--巡查范围 -->
              <el-form-item label="巡查范围：">
                <el-cascader
                  clearable
                  ref="cascader"
                  v-model="taskFormData.adcodes"
                  placeholder="请选择巡查范围"
                  :options="adcodesLevel1"
                  :props="{ multiple: true, emitPath: false, checkStrictly: true }"
                  :show-all-levels="false"
                  style="width: 100%"
                  @change="handleChange('cascader')"
                  @remove-tag="removeChange"
                >
                </el-cascader>
                <!-- 第一二种方法 -->
                <!-- :show-all-levels="false" 完整路径 -->
                <!-- <el-cascader
                  ref="cascader"
                  clearable
                  :props="cascaderProps"
                  :show-all-levels="false"
                  placeholder="请选择巡查范围"
                  v-model="taskFormData.adcodes"
                  style="width:100%"
                  @change="handleChange('cascader')"
                ></el-cascader> -->
              </el-form-item>
              <el-form-item label="巡查主体：">
                <el-select v-model="taskFormData.parentId" clearable placeholder="请选择巡查主体" style="width: 100%">
                  <el-option v-for="item in childSubject" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="主体类型：">
                <el-select
                  v-model="taskFormData.principalTypeIds"
                  multiple
                  placeholder="请选择主体类型"
                  style="width: 100%"
                >
                  <el-option v-for="item in subjectType" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="计划描述：">
                <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="taskFormData.planDescribe">
                </el-input>
              </el-form-item>
              <el-form-item label="实施周期：">
                <el-input-number
                  v-model="taskFormData.frequencyCount"
                  controls-position="right"
                  :min="1"
                  style="width: 30%; margin-right: 20px"
                ></el-input-number>
                <el-select v-model="taskFormData.frequencyUnit" style="width: 30%" @visible-change="periodTime">
                  <el-option
                    v-for="item in frequencyOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="状态：">
                <el-radio v-model="taskFormData.status" :label="1">启用</el-radio>
                <el-radio v-model="taskFormData.status" :label="0">不启用</el-radio>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
      <span slot="footer">
        <el-button @click="resetFrom">重 置</el-button>
        <el-button type="primary" @click="subTaskPlan">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog title="计划详情" :visible.sync="taskDetailWin" width="30%">
      <el-row>
        <el-col :span="20">
          <div class="grid-content bg-purple">
            <el-form label-position="right" label-width="120px" :model="taskDetailData">
              <el-form-item label="计划编号：">
                <el-input v-model="taskDetailData.planNumber" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="计划名称：">
                <el-input v-model="taskDetailData.planName" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="开始时间：">
                <el-input v-model="taskDetailData.startTime" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="结束时间：">
                <el-input v-model="taskDetailData.endTime" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="任务类型：">
                <el-input v-model="taskDetailData.typeName" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="巡查范围：">
                <el-input v-model="taskDetailData.patrolGrid" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="巡查主体：">
                <el-input v-model="taskDetailData.patrolSubject" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="主体类型：">
                <el-input v-model="taskDetailData.subjectType" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="计划描述：">
                <el-input type="textarea" :rows="3" :disabled="true" v-model="taskDetailData.planDescribe"> </el-input>
              </el-form-item>
              <el-form-item label="实施周期：">
                <el-input v-model="taskDetailData.frequencyCount" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="状态：">
                <span :class="taskDetailData.status ? 'finishactive' : 'noactive'" class="active"></span>
                <span style="margin-left: 10px">{{ taskDetailData.status ? '启用' : '不启用' }}</span>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 处置 -->
    <el-dialog title="计划处置" :visible.sync="distributionWin" width="30%">
      <el-row>
        <el-col :span="20">
          <div class="grid-content bg-purple">
            <el-form label-position="right" label-width="150px" :model="distributionData">
              <el-form-item label="计划编号：">
                <el-input v-model="distributionData.planNumber" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="计划名称：">
                <el-input v-model="distributionData.planName" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="任务类型：">
                <el-input v-model="distributionData.typeName" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="处置岗位：">
                <el-select v-model="distributionData.userId" clearable placeholder="请选择处置岗位">
                  <el-option v-for="item in distributionRole" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="distributionWin = false">取 消</el-button>
        <el-button type="primary" @click="distributionTask">处 置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/project'
export default {
  data() {
    return {
      total: 0, // 数据总条数
      pageNum: 1, // 根据总条数生成的页码数
      limit: 10, // 每页多少条
      currentPage: 1, // 当前页
      // 表格数据源
      tableData: [],
      // 控制添加任务窗口
      createTaskWin: false,
      // 控制任务详情窗口
      taskDetailWin: false,
      // 控制任务处置窗口
      distributionWin: false,
      // 添加修改任务数据源
      taskFormData: {
        adcodes: [],
        endTime: '',
        frequencyCount: 0,
        frequencyUnit: 0,
        parentId: '',
        planDescribe: '',
        planName: '',
        principalTypeIds: [],
        startTime: '',
        status: 1,
        taskTypeId: '',
      },
      // 任务类型
      typeOption: [],
      // 巡查范围
      adcodesLevel1: [],
      // 巡查主体
      childSubject: [],
      // 主体类型
      subjectType: [],
      // 任务详情数据源
      taskDetailData: {},
      // 日期字典
      frequencyOption: [
        { value: 0, label: '天', disabled: false },
        { value: 1, label: '周', disabled: false },
        { value: 2, label: '月', disabled: false },
        { value: 3, label: '季', disabled: false },
        { value: 4, label: '年', disabled: false },
      ],
      // 任务进度字典
      plannedProgressOption: ['未创建', '未开始', '进行中', '已完成', '已超时'],
      // 任务状态字典
      taskPlanStatus: ['不启用', '启用'],
      // 处置
      distributionData: {
        planNumber: '',
        planName: '',
        typeName: '',
        id: '',
        userId: '',
      },
      // 处置角色数据源
      distributionRole: [],
      // 新增或者编辑
      changeStatus: 0,
    }
  },
  created() {
    this.getList({ current: this.currentPage, limit: this.limit })
  },
  methods: {
    // 分页多条件获取全部任务
    getList(data) {
      // 获取计划列表
      api.taskList(data).then(res => {
        if (res.code == '200') {
          let count = 0
          this.tableData = res.data.records
          this.tableData.forEach(item => {
            count++
            item.startTime = item.startTime.split(' ')[0]
            item.endTime = item.endTime.split(' ')[0]
            item.frequencyCount = item.frequencyCount + this.frequencyOption[item.frequencyUnit].label
            item.subjectType = Object.values(item.subjectType).join('，')
            item.patrolGrid = Object.values(item.patrolGrid).join('，')
            item.count = count
          })
          this.total = res.data.total
        }
      })
    },
    // 获取任务类型
    getTaskType() {
      api.taskType().then(res => {
        this.typeOption = []
        if (res.code == '200') {
          res.data.forEach(item => {
            this.typeOption.push({ value: item.id, label: item.typeName })
          })
        }
      })
    },
    // 选中，未做
    handleChange(value) {
      let checkedNodeList = this.$refs[value].getCheckedNodes()
      checkedNodeList = checkedNodeList.filter(item => {
        if (item.level == 1) {
          return item
        } else if (item.level == 2) {
          if (!item.parent.checked) {
            return item
          }
        } else if (item.level == 3) {
          if (!item.parent.parent.checked && !item.parent.checked) {
            return item
          }
        }
      })
      this.taskFormData.adcodes = checkedNodeList.map(item => item.value)
    },
    // 删除tag
    removeChange(value) {
      this.taskFormData.adcodes = this.taskFormData.adcodes.filter(item => item != value)
    },
    // 获取巡查范围
    getAddress() {
      api.getAddress({ pid: 441300 }).then(res => {
        if (res.code == '200') {
          res.data.forEach((item, index) => {
            this.adcodesLevel1.push({ value: item.zoningCode, label: item.name, children: [] })
            api.getAddress({ pid: item.id }).then(res => {
              if (res.code == '200' && res.data.length > 0) {
                res.data.forEach((cell, index2) => {
                  this.adcodesLevel1[index].children.push({ value: cell.zoningCode, label: cell.name, children: [] })
                  api.getAddress({ pid: cell.id }).then(res => {
                    if (res.code == '200' && res.data.length > 0) {
                      res.data.forEach(roll => {
                        this.adcodesLevel1[index].children[index2].children.push({
                          value: roll.zoningCode,
                          label: roll.name,
                        })
                      })
                    } else {
                      this.adcodesLevel1[index].children[index2].children = null
                    }
                  })
                })
              } else {
                this.adcodesLevel1[index].children = null
              }
            })
          })
        }
      })
    },
    // 获取巡查主体
    getSubject() {
      let data = {
        parentId: 0,
      }
      api.getChildSubject(data).then(res => {
        this.childSubject = []
        if (res.code == '200') {
          res.data.forEach(item => {
            this.childSubject.push({ value: item.id, label: item.principalName })
          })
        }
      })
    },
    // 获取主体类型
    getSubjectType(id) {
      let data = {
        parentId: id,
      }
      api.getChildSubject(data).then(res => {
        this.subjectType = []
        if (res.code == '200') {
          res.data.forEach(item => {
            this.subjectType.push({ value: item.id, label: item.principalName })
          })
        }
      })
    },
    // 添加任务计划
    addTaskPlan() {
      this.changeStatus = 1
      this.createTaskWin = true
      this.adcodesLevel1 = []
      ;(this.taskFormData = {
        adcodes: [],
        endTime: '',
        frequencyCount: 0,
        frequencyUnit: 0,
        parentId: '',
        planDescribe: '',
        planName: '',
        principalTypeIds: [],
        startTime: '',
        status: 1,
        taskTypeId: '',
      }),
        this.getTaskType()
      this.getSubject()
      this.getAddress()
    },
    // 提交任务计划
    subTaskPlan() {
      if (this.changeStatus) {
        api.addTaskPlan(this.taskFormData).then(res => {
          if (res.code == '200') {
            this.$message({
              type: 'success',
              message: '计划添加成功!',
            })
            this.createTaskWin = false
            this.getList({ current: this.currentPage, limit: this.limit })
          }
        })
      } else {
        api.updateTask(this.taskFormData).then(res => {
          if (res.code == '200') {
            this.$message({
              type: 'success',
              message: '任务修改成功!',
            })
            this.createTaskWin = false
            this.getList({ current: this.currentPage, limit: this.limit })
          } else {
            this.$message({
              type: 'warning',
              message: '计划修改失败!',
            })
          }
        })
      }
    },
    // 重置任务表单
    resetFrom() {
      this.taskFormData = {
        adcodes: [],
        endTime: '',
        frequencyCount: 0,
        frequencyUnit: 0,
        parentId: '',
        planDescribe: '',
        planName: '',
        principalTypeIds: [],
        startTime: '',
        status: 1,
        taskTypeId: '',
      }
    },
    // 详情
    openDetailWin(row) {
      this.taskDetailWin = true
      let data = {
        id: row.id,
      }
      api.taskDetail(data).then(res => {
        if (res.code == '200') {
          this.taskDetailData = res.data
          this.taskDetailData.startTime = this.taskDetailData.startTime.split(' ')[0]
          this.taskDetailData.endTime = this.taskDetailData.endTime.split(' ')[0]
          this.taskDetailData.patrolGrid = Object.values(this.taskDetailData.patrolGrid).join()
          this.taskDetailData.subjectType = Object.values(this.taskDetailData.subjectType).join()
          this.taskDetailData.frequencyCount =
            this.taskDetailData.frequencyCount + this.frequencyOption[this.taskDetailData.frequencyUnit].label
        }
      })
    },
    // 编辑
    openEditWin(row) {
      this.changeStatus = 0
      this.createTaskWin = true
      this.taskFormData.principalTypeIds = []
      this.taskFormData.adcodes = []
      this.adcodesLevel1 = []
      this.getTaskType()
      this.getSubject()
      this.getSubjectType(row.parentId)
      this.getAddress()
      api.taskDetail({ id: row.id }).then(res => {
        if (res.code == '200') {
          this.taskFormData.id = row.id
          this.taskFormData.planName = row.planName
          this.taskFormData.startTime = row.startTime + ' 00:00:00'
          this.taskFormData.endTime = row.endTime + ' 00:00:00'
          this.taskFormData.planDescribe = row.planDescribe
          this.taskFormData.taskTypeId = row.taskTypeId
          this.taskFormData.parentId = row.parentId
          this.taskFormData.adcodes = Object.keys(res.data.patrolGrid)
          this.taskFormData.frequencyUnit = res.data.frequencyUnit
          this.taskFormData.frequencyCount = res.data.frequencyCount
          this.taskFormData.status = row.status
          this.$nextTick(() => {
            this.taskFormData.principalTypeIds = Object.keys(res.data.subjectType).map(item => Number(item))
          })
        }
      })
    },
    // 删除
    openDeleteWin(row) {
      this.$confirm('是否删除此任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          api.deleteTaskPlan({ id: row.id }).then(res => {
            if (res.code == '200') {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          })
        })
    },
    // 打开处置界面
    openDistributionWin(row) {
      if (!row.status) {
        this.$message({
          message: '该任务处于禁用状态',
          type: 'warning',
        })
        return
      }
      this.distributionWin = true
      // 清空坐席员数组
      this.distributionRole = []
      this.distributionData.userId = ''
      // 查询所有坐席员
      let roleData = {
        roleId: 3,
      }
      // 任务信息
      let taskData = {
        id: row.id,
      }
      api.taskDetail(taskData).then(res => {
        if (res.code == '200') {
          this.distributionData.planNumber = res.data.planNumber
          this.distributionData.planName = res.data.planName
          this.distributionData.typeName = res.data.typeName
          this.distributionData.id = row.id
        }
      })
      api.roleTest(roleData).then(res => {
        if (res.code == '200') {
          res.data.forEach(item => {
            this.distributionRole.push({ value: item.userId, label: item.fullName })
          })
        }
      })
    },
    // 处置功能
    distributionTask() {
      let data = {
        id: this.distributionData.id,
        userId: this.distributionData.userId,
      }
      if (!data.userId) {
        this.$message({
          message: '请选择处置岗位',
          type: 'warning',
        })
        return
      }
      api.distributionPlan(data).then(res => {
        if (res.code == '200') {
          this.distributionWin = false
          this.$message({
            message: '处置成功',
            type: 'success',
          })
        }
      })
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList({ current: this.currentPage, limit: this.limit })
    },
    handleSizeChange(val) {
      this.limit = val
      this.getList({ current: this.currentPage, limit: this.limit })
    },
    // 根据选择时间限制选择日期
    periodTime() {
      if (this.taskFormData.startTime && this.taskFormData.endTime) {
        let time =
          Math.abs(this.taskFormData.endTime.slice(0, 4) - this.taskFormData.startTime.slice(0, 4)) * 365 +
          (this.taskFormData.endTime.slice(5, 7) - this.taskFormData.startTime.slice(5, 7)) * 30 +
          (this.taskFormData.endTime.slice(8, 10) - this.taskFormData.startTime.slice(8, 10))
        if (time < 7) {
          this.frequencyOption.forEach(item => {
            if (item.value >= 1) {
              item.disabled = true
            } else {
              item.disabled = false
            }
          })
        } else if (time < 30) {
          this.frequencyOption.forEach(item => {
            if (item.value >= 2) {
              item.disabled = true
            } else {
              item.disabled = false
            }
          })
        } else if (time < 90) {
          this.frequencyOption.forEach(item => {
            if (item.value >= 3) {
              item.disabled = true
            } else {
              item.disabled = false
            }
          })
        } else if (time < 365) {
          this.frequencyOption.forEach(item => {
            if (item.value >= 4) {
              item.disabled = true
            } else {
              item.disabled = false
            }
          })
        } else {
          this.frequencyOption.forEach(item => {
            item.disabled = false
          })
        }
      }
    },
  },
  watch: {
    'taskFormData.parentId'(newVal) {
      this.taskFormData.principalTypeIds = []
      this.getSubjectType(newVal)
    },
  },
}
</script>

<style lang="scss" scoped>
.select {
  background-color: pink;
  margin-bottom: 30px;
}
.add-plan {
  margin-bottom: 10px;
}
.show-plan {
  margin-bottom: 20px;
}
.pageBox {
  text-align: right;
}
.el-date-editor.el-input,
.el-input--prefix.el-input--suffix.el-date-editor--date {
  width: 100%;
}
.active {
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 10px;
}
.noactive {
  background-color: gray;
}
.onactive {
  background-color: orange;
}
.finishactive {
  background-color: green;
}
.outactive {
  background-color: red;
}
</style>
